/*
 * Copyright 2002-2006 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.tigris.jasmincc.implementation;

import java.util.*;
import org.tigris.jasmincc.*;
import org.tigris.jasmincc.framework.*;
import org.tigris.mappedlexer.validator.Validator;
import org.tigris.mappedlexer.validator.VerifyHub;

/**
 * A template for parsing regular expression.
 * 
 * @author Sam Huang
 * 
 */
public class RegexRegionProduction extends AbstractProduction {

	protected JavaCCModel javaccModel = null;

	protected Production regularExpressionProduction = null;

	protected Map<String, Object> cache = null;

	public static final String[] KEYWORDS = { "TOKEN", "SKIP", "MORE",
			"SPECIAL_TOKEN" };

	public void parse() throws Exception {
		RegexRegion rr = new RegexRegion();
		List<String> headers = null;

		NamingManager namingManager = (NamingManager) cache
				.get("namingManager");

		tk = lexer.nexttok(new String[] { "<", "TOKEN", "SKIP", "MORE",
				"SPECIAL_TOKEN" });
		headers = parseHeaders(namingManager);
		rr.setRegexRegionType(tk);
		rr.setHeaders(headers);

		// lexer.setDump(false);
		parseIgnoreCase();
		tk = lexer.nexttok(false, SYM_LEFT_BRACE);
		regularExpressionProduction.setLexer(lexer);
		do {
			regularExpressionProduction.parse();
			List<String> tokens = ((StorableProduction) regularExpressionProduction)
					.getTokens();

			RegexSpec regexSpec = new RegexSpec();
			regexSpec.setName(tokens.get(0));
			if (tokens.size() > 1) {
				regexSpec.setValue(tokens.get(1));
			}

			tk = lexer.nexttok(false, SYM_VERTICAL_LINE, SYM_RIGHT_BRACE,
					SYM_LEFT_BRACE, SYM_COLON);
			if (tk.equals(SYM_LEFT_BRACE)) {
				tk = lexer.skipTo(SYM_LEFT_BRACE_CHAR);
				regexSpec.setBlock(tk);
				// attachToJavaccModel(tokens[0], tokens[1], tk);
				tk = lexer.nexttok(false, SYM_VERTICAL_LINE, SYM_RIGHT_BRACE,
						SYM_COLON);
			} else {
				// attachToJavaccModel(tokens[0], tokens[1], null);
			}
			// token name
			if (tk.equals(SYM_COLON)) {
				tk = lexer.nexttok();
				tk = namingManager.updateRef(tk);
				regexSpec.setToken(tk);
				tk = lexer.nexttok(false, SYM_VERTICAL_LINE, SYM_RIGHT_BRACE);
			}
			rr.addRegexSpec(regexSpec);
		} while (tk.equals(SYM_VERTICAL_LINE));
		javaccModel.addRegexRegion(rr);
		// lexer.setDump(true);
	}

	/**
	 * @param headers
	 * @param namingManager
	 * @throws Exception
	 * @throws UnsupportedOperationException
	 */
	private List<String> parseHeaders(NamingManager namingManager)
			throws Exception, UnsupportedOperationException {
		List<String> headers = new ArrayList<String>();
		if (tk.equals("<")) {
			// HeadersSingleton.getInstance().clear();
			// lexer.print(tk);
			do {
				tk = lexer.nexttok(new String[] { "*" },
						new Validator[] { VerifyHub.IDENTIFIER });
				logger.info(lexer.getPosition());
				logger.info(lexer.getLine());
				if (!tk.equals("*")) {
					tk = namingManager.updateRef(tk);
					// HeadersSingleton.getInstance().addHeader(tk);
					headers.add(tk);
				}
				tk = lexer.nexttok(false, ",", ">"); // >
			} while (tk.equals(","));
			tk = lexer.nexttok(false, KEYWORDS);
		}
		return headers;
	}

	/**
	 * @throws Exception
	 */
	protected void parseIgnoreCase() throws Exception {
		tk = lexer.nexttok(false, SYM_COLON, "[");
		if (tk.equals("[")) {
			tk = lexer.nexttok(false, "IGNORE_CASE");
			tk = lexer.nexttok(false, "]");
			tk = lexer.nexttok(false, SYM_COLON);
		}
	}

	public void setRegularExpressionProduction(
			StorableProduction regularExpressionProduction) {
		this.regularExpressionProduction = regularExpressionProduction;
	}

	/**
	 * @param tokensManager
	 *            the tokensManager to set
	 */
	public void setJavaccModel(JavaCCModel javaccModel) {
		this.javaccModel = javaccModel;
	}

	/**
	 * @param cache
	 *            the cache to set
	 */
	public void setCache(Map<String, Object> cache) {
		this.cache = cache;
	}
}
